﻿using System.ServiceModel.DomainServices.Client;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using PhotoManagerApp.Web.DomainServices;
using PhotoManagerApp.Web.EF;
using System.Linq;
using System.Windows.Controls;
using System.IO;
using System.Windows;

namespace PhotoManagerApp.ViewModels
{
    public class ProfileViewModel : ViewModelBase
    {
        private readonly EroticDomainContext context = new EroticDomainContext();

        public ProfileViewModel()
        {
            RefreshUser();
            AddCommand = new RelayCommand(Add);
            DeleteCommand = new RelayCommand(Delete);
            UpdateCommand = new RelayCommand(Update);
           
            DeleteImageCommand = new RelayCommand(DeleteImage);
            UpdateImageCommand = new RelayCommand(UpdateImage);
            this.newFolder = new Folder();
            this.NewImage = new Web.EF.Image();
        }

        public EntitySet<Web.EF.Image> Images
        {
            get
            {
                return context.Images;
            }
        }

        public void RefreshFolders()
        {
            context.Folders.Clear();
            var query = context.GetFoldersQuery().Where(f => f.UserID == LoggedInUser.UserId);
            context.Load(query, lo =>
            {
            }, null);
        }

        private Folder currentFolder;
        public Folder CurrentFolder
        {
            get
            {
                return this.currentFolder;
            }
            set
            {
                if (this.currentFolder != value)
                {
                    this.currentFolder = value;
                    LoadImages();
                    RaisePropertyChanged("CurrentFolder");
                }
            }
        }

        private aspnet_Users loggedInUser;
        public aspnet_Users LoggedInUser
        {
            get
            {
                return loggedInUser;
            }
            set
            {
                if (this.loggedInUser != value)
                {
                    loggedInUser = value;
                    RaisePropertyChanged("LoggedInUser");
                }
            }
        }

        private Folder newFolder;
        public Folder NewFolder
        {
            get
            {
                return this.newFolder;
            }
            set
            {
                if (this.newFolder != value)
                {
                    this.newFolder = value;
                    RaisePropertyChanged("NewFolder");
                }
            }
        }

        private Web.EF.Image currentImage;
        public Web.EF.Image CurrentImage
        {
            get
            {
                return currentImage;
            }
            set
            {
                if (this.currentImage != value)
                {
                    currentImage = value;
                    RaisePropertyChanged("CurrentImage");
                }
            }
        }

        private PhotoManagerApp.Web.EF.Image newImage;
        public PhotoManagerApp.Web.EF.Image NewImage
        {
            get
            {
                return newImage;
            }
            set
            {
                if (this.newImage != value)
                {
                    newImage = value;
                    RaisePropertyChanged("NewImage");
                }
            }
        }

        private void LoadImages()
        {
            if (this.CurrentFolder != null)
            {
                context.Images.Clear();
                var query = context.GetImagesQuery().Where(f => f.FolderID == CurrentFolder.FolderID);
                context.Load(query, lo =>
                {

                }, null);
            }
        }
        public EntitySet<Folder> Folders
        {
            get
            {
                return context.Folders;
            }
        }

        public ICommand AddCommand
        {
            get;
            set;
        }
        public ICommand UpdateCommand
        {
            get;
            set;
        }
        public ICommand DeleteCommand
        {
            get;
            set;
        }
        public ICommand UpdateImageCommand
        {
            get;
            set;
        }
        public ICommand DeleteImageCommand
        {
            get;
            set;
        }

        internal void Add()
        {
            if (!this.newFolder.HasValidationErrors && !string.IsNullOrEmpty(this.newFolder.FolderName))
            {
                context.RejectChanges();
                this.NewFolder.UserID = LoggedInUser.UserId;

                context.Folders.Add(NewFolder);
                context.SubmitChanges(OnEditFolderCompleted, null);
            }
            else
            {
                this.newFolder = new Folder();
            }
        }

        private void OnEditFolderCompleted(SubmitOperation submitOp)
        {
            if (!submitOp.HasError)
            {
                RefreshFolders();
                NewFolder = new Folder();
                NewImage = new Web.EF.Image();
                CurrentFolder = Folders.FirstOrDefault();
            }
        }

        internal void Delete()
        {
            if (this.currentFolder != null)
            {
                context.RejectChanges();
                context.Folders.Remove(currentFolder);
                context.SubmitChanges(OnEditFolderCompleted, null);
            }
        }

        internal void Update()
        {
            if (this.currentFolder != null && (!this.currentFolder.HasValidationErrors) && !string.IsNullOrEmpty(this.CurrentFolder.FolderName))
            {
                context.SubmitChanges(OnEditFolderCompleted, null);
            }
        }

        internal void DeleteImage()
        {
            if (this.currentImage != null)
            {
                context.RejectChanges();
                context.Images.Remove(CurrentImage);
                context.SubmitChanges(OnEditFolderCompleted, null);
            }
        }

        internal void UpdateImage()
        {
            if (this.CurrentImage != null && (!this.CurrentImage.HasValidationErrors) && !string.IsNullOrEmpty(this.CurrentImage.ImageName))
            {
                context.SubmitChanges(OnEditFolderCompleted, null);
            }
        }

        public void RefreshUser()
        {
            context.aspnet_Users.Clear();
            var query = context.GetAspnet_UsersQuery();
            context.Load(query, lo =>
            {
                LoggedInUser = context.aspnet_Users.FirstOrDefault(u => u.UserName == WebContext.Current.User.Name);
                RefreshFolders();
            }, null);
        }

        internal void UploadPhoto()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            
            bool? ok = openFileDialog.ShowDialog();
            if (ok == true)
            {
                FileInfo fInfo = openFileDialog.File;
                FileStream fs = openFileDialog.File.OpenRead();
                this.NewImage.ImageName = fInfo.Name;

                byte[] bytes = null;

                using (fs)
                {
                    bytes = new byte[fs.Length];
                    long bytesToRead = fs.Length;
                    long bytesRead = 0;

                    while (bytesToRead > 0)
                    {
                        int n = fs.Read(bytes, (int)bytesRead, (int)bytesToRead);
                        if (n == 0)
                            break;

                        bytesRead += n;
                        bytesToRead -= n;
                    }
                }

                this.NewImage.ImageData = bytes;
            }
        }

        internal void AddPhoto()
        {
            if (!this.newImage.HasValidationErrors && CurrentFolder != null)
            {
                context.RejectChanges();
                this.NewImage.FolderID = CurrentFolder.FolderID;

                context.Images.Add(NewImage);
                LoggedInUser.Credits += 10;
                context.SubmitChanges(OnEditFolderCompleted, null);
                
            }
            else
            {
                this.newImage = new Web.EF.Image();
            }
        }
    }
}
